var SessionManager = (function (mod) {

    // 用于表示Session Manager的常量
    var TAG = 'MaxthonSessionManager';

    /* 改进： 现在仅存储record下的信息 */
    mod.record = {};
    mod.record.length = 0; // 已保存的Session数目
    mod.record.list = []; // 保存Session的名字（以时间日期命名）
    mod.record.sessions = {}; // 保存的Sessions

    var ls = window.localStorage; // LocalStorage
    var conf = runtime.ConfigManager; // ConfigManager
    var record = mod.record; //record指向SessionManager.record

    // 从 localStorage 中读取上次保存的record
    mod.Load = function () {
        if (ls[TAG]) {
            var tempObject = JSON.parse(ls[TAG]);
            record.length = tempObject.length;
            record.list = tempObject.list;
            // 将Object重新初始化为Session对象
            for (var it in tempObject.sessions) {
                var s = new mod.Session(tempObject.sessions[it]);
                record.sessions[s.key] = s;
            }
        }
    };

    // 将record存入localStorage
    mod.Save = function () {
        // 仅存储record
        ls[TAG] = JSON.stringify(record);
    };

    // 清除LocalStorage
    mod.ClearStorage = function () {
        if (ls[TAG]) {
            ls.removeItem(TAG);
        }
        mod.Load();
    };

    // 获取当前 [上次未关闭页面]，返回一个Session对象
    mod.GetLastSession = function () {
        var dataList = conf.get("maxthon.config",
            "browser.unclosed.tabs.last");
        var s = new mod.Session(mod.GetCurrentTime(), dataList);
        return s;
    };

    mod.AddSession = function (s) {
        // 确保要添加的Session不在列表中
        if (record.list.indexOf(s.key) == -1) {
            // 清除掉Session中已经打开过的链接
            s.ClearOpenedLinks();

            record.list.push(s.key);
            record.sessions[s.key] = s;
            record.length = record.list.length;
        } else {
            alert('该Session已经在列表中');
        }
    };

    // 将当前 [上次未关闭页面] 添加到SessionManager中
    mod.AddLastSession = function () {
        var s = mod.GetLastSession();
        mod.AddSession(s);
        mod.Save();
    };

    mod.GetSession = function (key) {
        var index = record.list.indexOf(key);
        if (index != -1) {
            return record.sessions[key];
        }
        return null;
    };

    mod.DeleteSession = function (key) {
        var index = record.list.indexOf(key);
        if (index != -1) {
            record.list.splice(index, 1);
            delete(record.sessions[key]);
            record.length = record.list.length;
        }
    };

    mod.LoadSession = function (str) {
        var s = new mod.Session(JSON.parse(str));
        mod.AddSession(s);
        mod.Save();
    };

    // 设置 [上次未关闭页面]
    mod.SetLastSessionByKey = function (key) {
        var s = mod.GetSession(key);
        if (s !== null) {
            var dataList = JSON.stringify(s.list);
            conf.set("maxthon.config",
                "browser.unclosed.tabs.last",
                dataList);
            alert('设置成功');
        } else {
            alert('不能设置为一个不存在的Session');
        }
    };

    mod.ClearCurrentSession = function () {
        var dummyStr =
            '[{"url":"dummy","title":"dummy","locked":false,"reopend":true,"build":true}]';
        conf.set("maxthon.config", "browser.unclosed.tabs.last",
            dummyStr);
        alert('清空成功');
    };

    /*
     * 返回Session Manager中是否有名为key的Session
     */
    mod.HasSession = function (key) {
        return record.list.indexOf(key) != -1;
    };

    mod.RenameSession = function (oldKey, newKey) {
        var s = mod.GetSession(oldKey);
        // 效验参数
        if (s === null) {
            alert('Session: ' + oldKey + ' 不存在');
            return;
        }
        if (mod.HasSession(newKey)) {
            alert('Session: ' + newKey + '已经存在，不能使用重复的名字');
            return;
        }
        // 重命名
        s.key = newKey;
        record.list[record.list.indexOf(oldKey)] = newKey;
        record.sessions[newKey] = s;
        delete(record.sessions[oldKey]);
    };

    // 获取并格式化当前时间，按照 2014-4-27 23:15:45 的格式
    mod.GetCurrentTime = function () {
        var curTime = new Date();
        var strDate = curTime.getFullYear() + '-' + (curTime.getMonth() +
                1) +
            '-' + curTime.getDate() + ' ' + curTime.getHours() +
            ':' + curTime.getMinutes() +
            ':' + curTime.getSeconds();
        return strDate;
    };

    return mod;

})(window.SessionManager || {});